#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
@Author: 李吉凯
@Email: lijk34925@hundsun.com
@Time: 2022/6/16 9:46
@File: 风险评估指标_权重调整.py
"""

import re

from qturboframe.lib.utils.by import By
from qturboframe.lib.webdriver import SeleniumError

from BladeFerm.Lib.Common import logger, data_processing
from BladeFerm.hui2_app import FE
from 基础公共脚本.公共方法_hui2 import open_menu
from 基础公共脚本.步骤检查_hui2 import check_ele_text

@data_processing
def risk_review_target_adjust(input_data=None, ui_expect=None):
    # 进入 风险等级查询 菜单 客户风险评估/风险等级查询
    open_menu({'子系统名称': '反洗钱系统', '菜单名称': '客户风险评估/风险评估指标'})

    # 选择 客户类型
    select_value = input_data.pop('客户类型', '个人')
    select = FE.select(idname={'xpath': '//label[contains(text(),"客户类型")]//following-sibling::div[contains(@class,"h-select")]'})
    select.set_value_for_single(select_value)

    # 点击 修改权重
    button_operate('修改权重')

    # 修改 权重
    for key, value in input_data.items():
        modify_weight(key, value)

    # 点击 保存 取消
    button_operate('保存')

    # 检查结果
    check_result()

    # 断言
    check_ele_text(input_data=None, ui_expect=ui_expect)

def check_result():
    tar = FE.driver.exist('xpath', './/div[contains(@class,"sum-score")]/span[contains(text(), "权重汇总")]')
    cur_text = tar.text
    cur_weight_score = int(re.search(r'\d+', cur_text).group())
    if cur_weight_score == 100:
        logger.info(f'调整后的结果是100，ok')
    else:
        logger.warning(f'调整后的结果是{cur_weight_score}，请检查输入数据')
        # raise SeleniumError(f'调整后的结果是{cur_weight_score}，请检查输入数据')

def button_operate(text='修改权重'):
    '''
    按钮操作和操作后的断言。
    :param text:
    :return:
    '''
    btn = FE.button('修改权重')
    if text == "修改权重":
        btn.click()
    else:
        btn = btn.element.find_element_by_attribute('xpath', './/following-sibling::button', f'text:{text}')
        btn.click()
    logger.info(f'点击 {text}')



def modify_weight(key, value):
    '''
    单个指标 数据调整
    :param adjust_data:
    :return:
    '''
    target_path = key
    adjust_status = value.get('是否启用', None)
    adjust_value = value.get('指标权重', None)
    target_row = target_path.split('/')
    target_name = target_row[-1]

    # 找表格对象
    base_table = FE.table_base(idname={'xpath': './/div[@class="amlrc-tables"]'})
    # 展开第1层表格
    first_table = expand_table(text=target_row[0], father=base_table._element)
    # 展开第2层表格
    target_table = expand_table(text=target_row[1], father=first_table)
    if len(target_row) > 2:
        # 展开第3层表格
        target_table = expand_table(text=target_row[2], father=target_table)

    # 找到指标的目标行
    target_table_row = found_target_row(target_name, target_table)
    # 指标 是否启用 设置
    if adjust_status:
        adjust_status = True if adjust_status == '是' else False
        set_status(adjust_status, target_table_row)

    # 指标 是否启用 设置
    if adjust_value:
        adjust_weight(target_name, adjust_value, target_table_row)

def expand_table(text, father):
    '''
    根据 text 查找所在的td单元格，查看是否展开？
    之后返回 td 所在的列表。
    :param text:
    :param father:
    :return:
    '''
    unexpand_status = r'h-icon-android-arrow-dropri'
    # onexpand_status = r'h-icon-android-arrow-dropdo'
    xpath_express = f'.//tr/*[contains(text(),"{text}")]'
    base_table_td = father.find_element_by_attribute('xpath', xpath_express)
    base_table_icon = base_table_td.exist('xpath', './i[contains(@class,"h-icon")]')
    if base_table_icon:
        base_table_icon_class = base_table_icon.get_attribute('class').split(' ')
        if unexpand_status in base_table_icon_class:
            base_table_icon.click()
            logger.info(f'展开 {text}')
        else:
            logger.info(f'{text} 已经展开。')
    else:
        logger.warning(f'{text} 没有前缀图标')
    cur_table_ele = base_table_td.find_element_by_attribute('xpath', './/ancestor::table[1]')
    return cur_table_ele

def found_target_row(text, father):
    '''
    查找 指标名称 所在的目标行
    :param text:
    :param father:
    :return:
    '''
    xpath_express = f'.//tr/td[contains(text(),"{text}")]'
    base_table_td = father.find_element_by_attribute('xpath', xpath_express)
    return base_table_td

def set_status(flag, father):
    '''
    设置 指标状态
    :param flag:
    :param father:
    :return:
    '''
    checked_flag = r'h-switch-checked'
    switch = father.find_element_by_attribute(By.XPATH, './/following-sibling::td//'
                                                        'span[contains(@class,"h-switch") and not(contains(@class,"h-switch-inner"))]')
    switch_class = switch.get_attribute('class').split(' ')
    if checked_flag in switch_class:
        cur_flag = True
    else:
        cur_flag = False
    if flag != cur_flag:
        switch.click()
        logger.info(f'切换状态为 {flag}')
    else:
        logger.warning(f'当前状态是 {flag}')

def adjust_weight(name, score, father):
    '''
    设置 指标得分
    :param name: 指标名称
    :param score: 指标得分
    :param father:
    :return:
    '''
    input_xpath = './/following-sibling::td//input[@class="h-input-number-input"]'
    input_ele = father.exist('xpath', input_xpath)
    if input_ele:
        input_ele.clear()
        input_ele.send_keys(str(score))
        logger.info(f'设置指标 {name} 得分为 {score}')
    else:
        raise SeleniumError(f'指标 {name} 不存在权重调整输入框，请检查！')